package com.itheima.tanhua.server.controller;

import com.aliyun.tea.utils.StringUtils;
import com.itheima.commons.holder.TokenHolder;
import com.itheima.commons.utils.JwtUtils;
import com.itheima.commons.utils.ValidateCodeUtils;
import com.itheima.tanhua.autoconfig.template.AipFaceTemplate;
import com.itheima.tanhua.autoconfig.template.OssTemplate;
import com.itheima.tanhua.dubbo.api.UserService;
import com.itheima.tanhua.model.domain.User;
import com.itheima.tanhua.model.domain.UserInfo;
import com.itheima.tanhua.model.dto.LoginRegInfoDto;
import com.itheima.tanhua.model.vo.LoginVerificationVo;
import io.jsonwebtoken.Claims;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.parsing.TokenHandler;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {
    @DubboReference
    private UserService userService;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    /**
     * 验证码
     * @param user
     * @return
     */
    @PostMapping("/login")
    public String getloginnum(@RequestBody User user) {
        //获取随机数
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        String s = code.toString();

        //将随机数存入redis
        Jedis jedis = new Jedis("localhost", 6379);
        jedis.set(user.getPhone(), s);
        //返回随机数
        return s;
    }

    /**
     * 登录
     * @param loginVerificationVo
     * @return
     * @throws Exception
     */
    @PostMapping("/loginVerification")
    public ResponseEntity getloginVerification(@RequestBody LoginVerificationVo loginVerificationVo) throws Exception {
        //获取电话
        String phone = loginVerificationVo.getPhone();
        //获取传入的验证码
        String verificationCode = loginVerificationVo.getVerificationCode();

        //获取存储的随机数（验证码）
        Jedis jedis = new Jedis("localhost", 6379);
        String code = jedis.get(phone);

        //返回错误
        if (StringUtils.isEmpty(code) || StringUtils.isEmpty(phone)) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("手机或验证码不能为空");
        }

        //设置isNew返回值
        boolean isNew = false;

        //验证码校验
        if (verificationCode.equals(code)) {
            //判断手机号是否已存在
            User user = userService.selectUserBymobile(phone);
            if (user == null) {
                //将手机号存入user表，token存入返回值map
                loginVerificationVo.setPassword("123456");
                userService.insertUserPhone(loginVerificationVo);
                isNew = true;
            }
        } else {
            throw new Exception("验证码失效");
        }

        //根据电话获取id
        Long id = userService.getUserIdByPhone(phone);

        //将电话及id存入token
        Map<String, Object> map = new HashMap<>();
        map.put("phone",phone);
        map.put("id",id);
        String token=JwtUtils.getToken(map);
        LoginVerificationVo vo=new LoginVerificationVo();
        vo.setIsNew(isNew);
        vo.setToken(token);
        return ResponseEntity.status(HttpStatus.OK).body(vo);
    }

    /**
     * 保存用户信息
     * @param authorization
     * @param loginRegInfoDto
     */
    @PostMapping("/loginReginfo")
    public void loginReginfo(@RequestHeader("Authorization")String authorization, @RequestBody LoginRegInfoDto loginRegInfoDto) {
        //获取id
        Claims claims = JwtUtils.getClaims(authorization);
        Integer id = (Integer) claims.get("id");

        //参数传递
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(loginRegInfoDto,userInfo);

        //设置id
        userInfo.setId(id.toString());

        //添加
        userService.addUserInfo(userInfo);
    }

    /**
     * 上传头像
     * @param headPhoto
     */
    @PostMapping("/loginReginfo/head")
    public ResponseEntity loginReginfohead(MultipartFile headPhoto) throws IOException {
        //获取id
        String id = TokenHolder.get();
        //获取文件大小，判断是否超过上限
        long size = headPhoto.getSize();
        if (size>2097152){
           return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件不能超过2M");
        }
        //获取文件类型 判断是否是支持的类型
        String contentType = headPhoto.getContentType();
        if (StringUtils.isEmpty(contentType)){
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败");
        }
        String[] split = contentType.split("/");
        if (!"png".equals(split[1])){
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件格式错误");
        }
        //调用OSS接口上传文件
        String upload = ossTemplate.upload(split[1], headPhoto.getInputStream());

        //人脸识别
        boolean detect = aipFaceTemplate.detect(upload);
//        if (!detect){
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("请上传正确的人脸照片");
//        }
        //存入数据库
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setAvatar(upload);
        boolean r=userService.updateUserInfo(userInfo);
        return r? ResponseEntity.ok(null) : ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("存入失败");
    }
}
